package io.dbw.modules.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.dbw.common.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class HttpUtils {
	
	public static CloseableHttpClient createDefault() {
        return HttpClientBuilder.create().build();
    }

    /**
     * get请求
     * @param url
     * @param param  请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return
     */
     public static JSONObject httpGet(String url, String param){
         JSONObject jsonResult = null;   //get请求返回结果
         try {
             CloseableHttpClient httpclient = HttpUtils.createDefault();
             //发送get请求
             HttpGet request = new HttpGet(url);
             URI realUrl = new URI(url +"?"+ param); 
             request.setURI(realUrl);
             HttpResponse response = httpclient.execute(request);
   
             /**请求发送成功，并得到响应**/
             if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                 /**读取服务器返回过来的json字符串数据**/
                 String strResult = EntityUtils.toString(response.getEntity(),"UTF-8");
                  
                 log.info("服务器返回结果："+strResult);
                 /**把json字符串转换成json对象**/
                 jsonResult = JSONObject.parseObject(strResult);
                 url = URLDecoder.decode(url, "UTF-8");
             } else {
                  System.out.println("get请求提交失败:" + url);
             }
         } catch (IOException e) {
             e.printStackTrace();
         }catch (Exception e) {
             e.printStackTrace();
         }
         return jsonResult;
     }
}